package register

import (
	"encoding/json"
	"log"
	"sync"
	"time"
)

type NodeAnnounce struct {
	Action         string     `json:"action"`
	Timeout        int64      `json:"timeout"`
	Nat            int64      `json:"nat"`
	Time           int64      `json:"time"`
	PeerId         string     `json:"peer_id"`
	PredictionPort int        `json:"prediction_port"`
	Proto          int32      `json:"protocol"`
	Sdps           []NodeSdps `json:"sdps"`
}

type NodeSdps struct {
	Offer         NodeOffer `json:"offer"`
	OfferId       int64     `json:"offer_id"`
	RemoteOfferId int64     `json:"remote_offer_id"`
}
type NodeOffer struct {
	Type string `json:"type"`
	Sdp  string `json:"sdp"`
	//Proto int32 `json:"protocol"`
}
type announceHandler struct {
	client *Client
}

func AcquireAnnounce() *NodeAnnounce {
	return announcePool.Get().(*NodeAnnounce)
}

func ReleaseAnnounce(na *NodeAnnounce) {
	//na.Reset()
	announcePool.Put(na)
}

var announcePool = &sync.Pool{
	New: func() interface{} {
		return &NodeAnnounce{}
	},
}

func (na *NodeAnnounce) Reset() {
	na.Action = na.Action[0:0]
	na.Sdps = na.Sdps[0:0]
	na.Timeout = 0
	na.Time = 0
	na.Nat = 0
	na.PeerId = na.PeerId[0:0]
	na.PredictionPort = 0
}

func (a *announceHandler) Handle(message []byte) {
	//node := AcquireAnnounce()
	//node.Reset()
	node := new(NodeAnnounce)
	if err := json.Unmarshal(message, node); err != nil {
		ReleaseAnnounce(node)
		log.Printf("[error]:announce handler json unmarshal err:%s", err.Error())
		return
	}
	log.Printf("[announceHandler]: get announce from uid:%s sdp: %d", node.PeerId, len(node.Sdps))
	node.Time = time.Now().Unix()
	a.client.SetNodeAnnounce(node)
	//TODO 关掉上报之后的回复
	//response := struct {
	//	Action   string `json:"action"`
	//	Interval int    `json:"interval"`
	//}{
	//	"announce",
	//	120,
	//}
	//err := a.client.jsonResponse(response)
	//if  err != nil {
	//	ReleaseAnnounce(node)
	//	return
	//}
}
